<?php
namespace api\modules\v1\models\shop;

use common\models\CacheKeys;
use common\models\Common;
use common\models\Functions;
use common\models\shop\GoodsOrder;
use common\models\Status;
use yii\base\Exception;
use api\modules\v1\models\user\User;
use Yii;

/**
 * 订单退款
 * @property int $id
 * @property string $name
 */
class GoodsOrderReturn extends \common\models\shop\GoodsOrderReturn
{

    /**
     * 退款申请
     * @return array
     */
    public function OrderApply()
    {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $userInfo = (new User())->checkUser();

            # 检查并发
            CacheKeys::checkFrequency($userInfo['id']);

            $post = Yii::$app->request->post();

            $orderNumber = (String) $post['order_number'];
            $reason = (String) $post['reason'];
            if (empty($orderNumber)) {
                throw new Exception('未知信息');
            }
            if (empty($reason)) {
                throw new Exception('请填写申请理由');
            }
            $returnNum = static::getCountByWhere(['order_number'=>$orderNumber]);
            if($returnNum >= 1){
                throw new Exception('请勿重复提交');
            }

            $orderInfo = GoodsOrder::getOneByWhere(['order_number' => $orderNumber]);
            if(empty($orderInfo) || $orderInfo['user_id'] != $userInfo['id']) {
                throw new Exception('未知订单信息');
            }
            if($orderInfo['status'] != Status::USER_GOODS_ORDER_STATUS_WAITING_SEND){
                throw new Exception('当前状态不允许申请退款');
            }

            //创建退款数据
            $data['user_id'] = $userInfo['id'];
            $data['order_number'] = $orderNumber;
            $data['goods_id'] = $orderInfo['goods_id'];
            $data['return_num'] = $orderInfo['num'];
            $data['order_id'] = $orderInfo['id'];
            $data['return_money'] = $orderInfo['real_money'];
            $data['reason'] = $reason;
            $data['status'] = Status::USER_GOODS_ORDER_SHENQING;
            $data['create_time'] = date('Y-m-d H:i:s');

            $info = static::insertData($data);
            //修改订单表状态
            GoodsOrder::updateData(['status'=>Status::USER_GOODS_ORDER_SHENQING],['order_number'=>$orderNumber]);
            if ($info == false) {
                throw new Exception('退款订单创建失败');
            }
            $trans->commit();
            return Functions::formatRestAPI(0, '申请成功，等待处理。');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

}
